<template>
  <el-dialog
    :title="upload.title"
    :visible.sync="upload.open"
    width="400px"
    :close-on-click-modal="false"
    :before-close="handleCloseDialog"
    append-to-body
    :modal-append-to-body="false"
  >
    <el-upload
      ref="upload"
      :limit="limit"
      :on-exceed="handleExceed"
      :before-upload="beforeUpload"
      :accept="accept"
      :headers="upload.headers"
      :action="upload.url"
      :data="upload.data"
      :disabled="upload.isUploading"
      :on-success="handleFileSuccess"
      :on-error="handleFileError"
      :auto-upload="false"
      :on-change="handleChange"
      :file-list="fileList"
      :http-request="uploadFile"
      drag
      multiple
    >
      <!-- <el-upload
      ref="upload"
      :limit="limit"
      :on-exceed="handleExceed"
      :before-upload="beforeUpload"
      :accept="accept"
      :headers="upload.headers"
      :action="upload.url"
      :data="upload.data"
      :disabled="upload.isUploading"
      :on-progress="handleFileUploadProgress"
      :on-success="handleFileSuccess"
      :auto-upload="false"
      :on-change="handleChange"
      :file-list="fileList"
      :http-request='uploadFile'
      drag
      multiple
      >-->
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">
        将文件拖到此处，或
        <em>点击上传</em>
      </div>

      <div class="el-upload__tip" style="color:red" slot="tip">提示：允许导入格式{{acceptOptions}}</div>
    </el-upload>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="submitFileForm">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getToken } from '@/utils/auth'
import SparkMD5 from 'spark-md5'
import {
  listFileblob,
  getFileblob,
  delFileblob,
  addFileblob,
  updateFileblob,
  exportFileblob,
} from '@/api/fileList/fileList'
import { batchUpload } from '@/api/sysPublic/blobRequest'
import store from '@/store/index'
import { getFunNo } from '@/utils/party'
import {NAME} from '@/utils/config'
export default {
  name: 'AddFiles',
  props: {
    //ctIdP默认没有，如有就传指定的ctIdP 如 员发展
    setCtIdP: {
      type: String,
      default: null,
    },
    taskreportList:{
      default:true,
      type:Boolean
    }
  },
  data() {
    return {
      store: store,
      //获取爷爷的内容
      // grandFather: this.$parent.$parent.$parent,

      //功能号 = 到底用props 还是这种？
      ctFunNo: getFunNo(this.taskreportList ?this.$route : this.$router.resolve({ name: NAME }).route),
      //业务ID
      ctIdP: '',
      //文件列表
      fileList: [],
      top: 'top',
      //  组织导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: '选择附件',
        // 是否禁用上传
        isUploading: false,

        // 设置上传的请求头部
        headers: {
          Authorization: 'Bearer ' + getToken(),
          // "Content-Type": "multipart/form-data"
        },
        //设置请求参数
        data: {
          // multipartFiles: '',
          ctIdP: '',
          ctFunNo: '',
          dtDate: new Date(),
        },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/spspublic/fileblob/batchUpload',
      },
      // 遮罩层
      loading: true,
      // 弹出层标题
      title: '',
      titleIcon: 'el-icon-edit-outline',
      // 是否显示弹出层
      open: false,
      limit: 10,
      // 总条数
      total: 0,
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      //文件允许列表
      acceptOptions: [],
      accept: '',
      formdata: {},
      successNumber: 0,
      failNumber: 0,
      subFunNo: null,
    }
  },
  mounted(){
    console.log(this.taskreportList);
  },
  created() {
    this.getDicts('allowed_upload_type').then((response) => {
      this.acceptOptions = response.data.map((item) => {
        return '.' + item.dictLabel
      })
      this.accept = this.acceptOptions.join(', ')
    })
  },
  watch: {
    // fileList(val){
    //   console.log('fileList')
    //   console.log(val)
    // }
  },
  methods: {
    beforeUpload(file) {},
    handleChange(file, fileList) {
      // console.log('handleChange')
      // console.log(file.size)
      if (file.name.indexOf('..') !== -1) {
        this.$message.error('文件名不允许包含【..】字符串')
        // let temp=fileList.filter((item)=>{
        //   return item.uid!=file.uid
        //   });
        fileList.pop()
        this.fileList = fileList
        return
      }
      const isLitXM = file.size / 1024 / 1024 < 30
      if (!isLitXM) {
        this.$message({
          message: '上传文件大小不能超过 30MB!',
          type: 'warning',
        })
        fileList.pop()
        this.fileList = fileList
        return
      }
      let existFile = fileList
        .slice(0, fileList.length - 1)
        .find((f) => f.name === file.name)
      if (existFile) {
        this.$message.error('当前文件已经存在!')
        fileList.pop()
        this.fileList = fileList
      }
    },
    handleOpenDialog(e) {
      // console.log('handleOpenDialog')
      // //设置爷爷级别的激活标签
      // this.grandFather.activeTab = 'tabFiles'
      // //获取爷爷级别的功能号
      // this.funNo = this.grandFather.funNo
      this.subFunNo =
        this.store.state.dynamic.singleStore['main' + this.ctFunNo].subFunNo
      this.ctFunNo = getFunNo(this.taskreportList ?this.$route : this.$router.resolve({ name: NAME }).route)
      if (this.ctFunNo != '9999') {
        if (this.setCtIdP) {
          this.ctIdP = this.setCtIdP
        } else {
          this.ctIdP =
            this.store.state.dynamic.singleStore[
              'main' + this.ctFunNo
            ].subSingleStore['sub' + this.subFunNo].ctId
        }
        if(e) {
          this.ctIdP = e
        }
      }  else if(e) {
        this.ctIdP = e
      } else {
        if (this.subFunNo == '1501') {
          this.ctIdP = this.setCtIdP
        } else {
          this.ctIdP = this.store.state.dynamic.singleStore[
              'main' + this.ctFunNo
            ].subSingleStore['sub' + this.subFunNo].ctId
        }
      }
      this.upload.data.ctFunNo = this.ctFunNo
      this.upload.data.ctIdP = this.ctIdP
      this.upload.open = true

      //初始化
      //this.initForm();
    },
    handleCloseDialog() {
      this.successNumber = 0
      this.failNumber = 0
      this.$refs.upload.clearFiles()
      this.upload.open = false
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      // console.log('handleFileUploadProgress')
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      // console.log('handleFileSuccess')
      // console.log(fileList)
      this.upload.open = false
      this.upload.isUploading = false
      if (fileList.length == 1) {
        this.$refs.upload.clearFiles()
        this.$alert(response.msg, '导入结果', {
          dangerouslyUseHTMLString: true,
        })
      }
      this.$emit('refreshFileList')
      this.$emit('fileResponse', response)
    },
    uploadFile(params) {
      console.log(params);
      // console.log('uploadFile',params);
      // console.log(this.$refs.upload)
      const _file = params.file
      var formData = new FormData()
      formData.append('ctIdP', params.data.ctIdP)
      formData.append('ctFunNo', params.data.ctFunNo)
      formData.append('dtDate', params.data.dtDate)
      formData.append('file', _file)
      batchUpload(formData)
        .then((res) => {
          // console.log(this.fileList)
          if (res.code == 200) {
            this.successNumber++
          } else {
            this.failNumber++
          }
          if (
            this.successNumber + this.failNumber ==
            this.$refs.upload.uploadFiles.length
          ) {
            this.showResultConfirm()
            this.$emit('refreshFileList')
            this.$emit('fileResponse', res)
          }
        })
        .catch((err) => {
          this.failNumber++
          if (
            this.successNumber + this.failNumber ==
            this.$refs.upload.uploadFiles.length
          ) {
            this.showResultConfirm()
            this.$emit('refreshFileList')
            this.$emit('fileResponse', res)
          }
        })
    },
    handleFileError(err, file, fileList) {
      console.dir(err)
      this.$alert('上传出错')
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 ${this.limit} 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      )
    },
    // 提交上传文件
    submitFileForm() {

      this.$refs.upload.submit()
      // this.$refs.upload.clearFiles();
    },
    showResultConfirm() {
      this.$confirm(
        `上传成功${this.successNumber}个，失败${this.failNumber}个`,
        '提示',
        {
          confirmButtonText: '确定',
          showCancelButton: false,
          type: 'success',
        }
      )
        .then(() => {
          this.handleCloseDialog()
        })
        .catch(() => {
          this.handleCloseDialog()
        })
    },
    // 取消按钮
    cancel() {
      this.$refs.upload.clearFiles()
      this.upload.open = false
      //this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        ctId: null,
        ctIdP: null,
        ctName: null,
        bBlob: null,
        ctType: null,
        ctFile: null,
        dtDate: null,
        ctState: null,
        ctHtml: null,
      }
      this.resetForm('form')
    },
  },
}
</script>

<style scoped>
</style>
